package com.topscomm.mpm.xxlJob;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.topscomm.basic.BasicEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.cbo.service.impl.CboApprovalNodeInsService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.MpmProjectBidScoreEntity;
import com.topscomm.mpm.pojo.MpmProjectEntity;
import com.topscomm.mpm.pojo.MpmProjectSaleEntity;
import com.topscomm.mpm.service.impl.MpmProjectBidScoreService;
import com.topscomm.mpm.service.impl.MpmProjectService;
import com.topscomm.mpm.service.impl.MpmProjectTaskService;
import com.topscomm.mpm.utils.GetContextUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.TapService;
import com.topscomm.tap.common.DatacodeCache;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author houyuhang
 * @date 2022/04/24
 * @description: 项目评分细则完成情况
 * @modify:
 */
@JobHandler(value = "bidScoreStateJob")
@Component
public class BidScoreStateJob extends IJobHandler {
    private static final Logger log = LoggerFactory.getLogger(BidScoreStateJob.class);
    @Autowired
    public MpmProjectService mpmProjectService;
    @Autowired
    public MpmProjectBidScoreService mpmProjectBidScoreService;
    public static final long DAY7_MILLSECONDS = 24 * 60 * 60 * 1000L * 7;// 以毫秒为单位，7天
    public static final long DAY11_MILLSECONDS = 24 * 60 * 60 * 1000L * 11;// 以毫秒为单位，11天
    @Override
    public ReturnT<String> execute(String param) {
        try {
            // 获取立项审批结束的项目
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(" state = 9 ");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("whereSql", sql.toString());
            List<Map<String, Object>> mpmProjectList = mpmProjectService.queryMap(dataMap, "queryPolymarizationMapByWhere");
            // 获取所有一次自评完成的项目
            Map<String, List<MpmProjectBidScoreEntity>> firstScoreMap = this.queryFirstScore();
            // 获取所有二次自评完成的项目
            Map<String, List<MpmProjectBidScoreEntity>> secondScoreMap = this.querySecondScore();
            // 获取必填评分细则的项目（项目为A级项目且采购模式不为“单一来源采购”、“服务招标采购”、“其他”、“电商化采购”）
            Map<String, List<Map<String, Object>>> needBidScoreMap = this.queryNeedBidScore();
            List<Map<String, Object>> updateMap = new ArrayList<>();
            for(Map<String, Object> mpmProjectMap : mpmProjectList) {
                Map<String, Object> tempMap = new HashMap<>();
                String id = ConvertUtil.convertToString(mpmProjectMap.get("id"));
                String projectcode = ConvertUtil.convertToString(mpmProjectMap.get("projectcode"));
                if (CollectionUtil.isEmpty(needBidScoreMap.get(projectcode))) {
                    if (CollectionUtil.isEmpty(firstScoreMap.get(projectcode)) && CollectionUtil.isEmpty(secondScoreMap.get(projectcode))) {
                        tempMap.put("id", id);
                        tempMap.put(MpmProjectEntity.FieldBidscorestate, MpmSystemConst.BidScoreState.unfinishWrite);
                        updateMap.add(tempMap);
                        continue;
                    } else {
                        tempMap.put("id", id);
                        tempMap.put(MpmProjectEntity.FieldBidscorestate, MpmSystemConst.BidScoreState.finishWrite);
                        updateMap.add(tempMap);
                        continue;
                    }
                }
                // 历史数据处理，标记bidscoreflag为1的项目处理为未到期
                if ("1".equals(ConvertUtil.convertToString(mpmProjectMap.get("bidscoreflag")))) {
                    tempMap.put("id", id);
                    tempMap.put(MpmProjectEntity.FieldBidscorestate, MpmSystemConst.BidScoreState.noOverdue);
                    updateMap.add(tempMap);
                    continue;
                }
                // 项目完成二次自评，赋值为二次自评
                if (!CollectionUtil.isEmpty(secondScoreMap.get(projectcode))) {
                    tempMap.put("id", id);
                    tempMap.put(MpmProjectEntity.FieldBidscorestate, MpmSystemConst.BidScoreState.secondScore);
                    updateMap.add(tempMap);
                    continue;
                }
                // 项目完成一次自评
                if (!CollectionUtil.isEmpty(firstScoreMap.get(projectcode))) {
                    // 完成一次自评，赋值状态一次自评或二次超期
                    this.finishFirstScore(updateMap, mpmProjectMap);
                } else {
                    // 未完成一次自评，赋值状态一次超期或未到期
                    this.noFinishFirstScore(updateMap, mpmProjectMap);
                }
            }
            mpmProjectService.updateBatchMap(updateMap);
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            log.error("项目评分细则获取失败，请联系管理员！", e);
            return new ReturnT<>(ReturnT.FAIL_CODE, e.getMessage());
        }
    }
    /**
     * @author houyuhang
     * @date 2022/04/24
     * @description: 获取所有一次自评完成的项目
     * @modify:
     */
    public Map<String, List<MpmProjectBidScoreEntity>> queryFirstScore() {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" {0} = '1' and state = 9 ", MpmProjectBidScoreEntity.FieldTimes);
        List<MpmProjectBidScoreEntity> mpmProjectBidScoreEntities = mpmProjectBidScoreService.queryByWhere(sql.toString());
        Map<String, List<MpmProjectBidScoreEntity>> mpmProjectBidScoreMap = mpmProjectBidScoreEntities.stream()
                .collect(Collectors.groupingBy(MpmProjectBidScoreEntity::getProjectcode));
        return mpmProjectBidScoreMap;
    }
    /**
     * @author houyuhang
     * @date 2022/04/24
     * @description: 获取所有一次自评完成的项目
     * @modify:
     */
    public Map<String, List<MpmProjectBidScoreEntity>> querySecondScore() {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" {0} = '2' and state = 9 ", MpmProjectBidScoreEntity.FieldTimes);
        List<MpmProjectBidScoreEntity> mpmProjectBidScoreEntities = mpmProjectBidScoreService.queryByWhere(sql.toString());
        Map<String, List<MpmProjectBidScoreEntity>> mpmProjectBidScoreMap = mpmProjectBidScoreEntities.stream()
                .collect(Collectors.groupingBy(MpmProjectBidScoreEntity::getProjectcode));
        return mpmProjectBidScoreMap;
    }
    /**
     * @author houyuhang
     * @date 2022/04/24
     * @description: 完成一次自评的项目赋值
     * @modify:
     */
    public void finishFirstScore(List<Map<String, Object>> updateMap, Map<String, Object> mpmProjectMap) throws ParseException {
        Map<String, Object> tempMap = new HashMap<>();
        // 由于历史数据原因，可能存在开标日期为空的情况
        if (ObjectUtil.isEmpty(mpmProjectMap.get("bidenddate"))) {
            tempMap.put("id", mpmProjectMap.get("id"));
            tempMap.put(MpmProjectEntity.FieldBidscorestate, MpmSystemConst.BidScoreState.secondOverdue);
            updateMap.add(tempMap);
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = sdf.parse(sdf.format(new Date()));
        Date bidEndDate = sdf.parse(sdf.format(mpmProjectMap.get("bidenddate")));
        // 如果一次招标完成二次未完成，超过挂网日期后七天，则将状态赋值为二次超期，否则赋值为一次自评
        if (now.getTime() - bidEndDate.getTime() > DAY7_MILLSECONDS) {
            tempMap.put("id", mpmProjectMap.get("id"));
            tempMap.put(MpmProjectEntity.FieldBidscorestate, MpmSystemConst.BidScoreState.secondOverdue);
            updateMap.add(tempMap);
        } else {
            tempMap.put("id", mpmProjectMap.get("id"));
            tempMap.put(MpmProjectEntity.FieldBidscorestate, MpmSystemConst.BidScoreState.firstScore);
            updateMap.add(tempMap);
        }
    }
    /**
     * @author houyuhang
     * @date 2022/04/24
     * @description: 未完成一次自评的项目赋值
     * @modify:
     */
    public void noFinishFirstScore(List<Map<String, Object>> updateMap, Map<String, Object> mpmProjectMap) throws ParseException {
        Map<String, Object> tempMap = new HashMap<>();
        if (ObjectUtil.isEmpty(mpmProjectMap.get("finishdate"))) {
            tempMap.put("id", mpmProjectMap.get("id"));
            tempMap.put(MpmProjectEntity.FieldBidscorestate, MpmSystemConst.BidScoreState.noOverdue);
            updateMap.add(tempMap);
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = sdf.parse(sdf.format(new Date()));
        Date finishDate = sdf.parse(sdf.format(mpmProjectMap.get("finishdate")));
        // 如果一次招标未完成，超过立项结束日期11天，则将状态赋值为一次超期
        if (now.getTime() - finishDate.getTime() > DAY11_MILLSECONDS) {
            tempMap.put("id", mpmProjectMap.get("id"));
            tempMap.put(MpmProjectEntity.FieldBidscorestate, MpmSystemConst.BidScoreState.firstOverdue);
            updateMap.add(tempMap);
        } else {
            tempMap.put("id", mpmProjectMap.get("id"));
            tempMap.put(MpmProjectEntity.FieldBidscorestate, MpmSystemConst.BidScoreState.noOverdue);
            updateMap.add(tempMap);
        }
    }
    /**
     * @author houyuhang
     * @date 2022/04/24
     * @description: 获取必填评标细则的项目
     * @modify:
     */
    public Map<String, List<Map<String, Object>>> queryNeedBidScore() {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" state = 9 and {0} = '{1}' and {2} = '{3}' ",MpmProjectEntity.FieldProjectlevel, MpmSystemConst.ProjectLevel.A,
                MpmProjectSaleEntity.FieldPurchasepattern, MpmSystemConst.PurchasePattern.chanpinBid);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("whereSql", sql.toString());
        List<Map<String, Object>> mpmProjectList = mpmProjectService.queryMap(dataMap, "queryPolymarizationMapByWhere");
        Map<String, List<Map<String, Object>>> mpmProjectMap = mpmProjectList.stream()
                .collect(Collectors.groupingBy(item -> ConvertUtil.convertToString(item.get("projectcode"))));
        return mpmProjectMap;
    }
}
